package com.yds.bluetooth

import android.text.TextUtils
import java.util.Locale

/**
 * 只处理大段序数据，
 * 大段序：必须高位在前，低位在后。
 */
object DataConvert {
    /**
     * byte数组转16进制字符串
     */
    fun toHexString(value: ByteArray?): String {
        var ret = ""
        if (null == value) {
            return ret
        }
        for (i in value.indices) {
            var hex = Integer.toHexString(value[i].toInt() and 0xFF)
            if (hex.length == 1) {
                hex = "0$hex"
            }
            ret += hex
        }
        return if (!TextUtils.isEmpty(ret)) {
            ret.uppercase(Locale.getDefault())
        } else ret
    }

    fun hexStringToBytes(hexStr: String): ByteArray {
        val hexString = hexStr.uppercase(Locale.getDefault())
        val length = hexString.length / 2
        val hexChars = hexString.toCharArray()
        val d = ByteArray(length)
        for (i in 0 until length) {
            val pos = i * 2
            d[i] = (charToByte(hexChars[pos]).toInt() shl 4 or charToByte(hexChars[pos + 1]).toInt()).toByte()
        }
        return d
    }

    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private fun charToByte(c: Char): Byte {
        return "0123456789ABCDEF".indexOf(c).toByte()
    }
}